package com.ayh.campusfun.common.core.hack;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * @author ayh
 * @create 2021/3/24 0024 11:22
 */


public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {

    @Value("${fun.api-package}")
    private String apiPackagePath;

        //    重写spring boot生成请求地址处理方法
        @Override
        protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
            RequestMappingInfo mappingInfo =  super.getMappingForMethod(method, handlerType);
            if (mappingInfo != null){
                String prefix = this.getPrefix(handlerType);
                return RequestMappingInfo.paths(prefix).build().combine(mappingInfo);
            }
            return mappingInfo;
        }

        private String getPrefix(Class<?> handlerType){
            String packageName = handlerType.getPackage().getName();
            return packageName
                    .replaceAll(this.apiPackagePath, "")
                    .replace(".", "/");
        }
}
